package com.springboot.logback.config;

import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

//@Component
//@ServletComponentScan
//@WebFilter(urlPatterns = "/userInfo/*", filterName = "apiFilter")
public class ApiFilter implements Filter {
    private static final String API_FILTER_LOGGER_NAME = "apiFilterLogger";

    @Value("${api.filter.enable:false}")
    private boolean apiFilerEnable;
    private Logger logger = LoggerFactory.getLogger(API_FILTER_LOGGER_NAME);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (apiFilerEnable) {
            HttpServletRequest httprequest = (HttpServletRequest) request;
            String currentIp = request.getRemoteAddr();
            Enumeration<String> e = httprequest.getHeaderNames();
            logger.info("============================API Request Start==============================");
            String msg = String.format(">>API Request:[%s] [%s]", httprequest.getMethod(), httprequest.getRequestURL());
            logger.info(msg);
            logger.info(">>>>>Remote Addr:" + httprequest.getRemoteAddr());
            logger.info(">>>>>Query String:" + httprequest.getQueryString());
            logger.info("============Header=================");
            while (e.hasMoreElements()) {
                String k = e.nextElement();
                logger.info(">>>>>" + k + " = " + httprequest.getHeader(k));
            }

            Map<String, String[]> paramMap = httprequest.getParameterMap();
            logger.info("============Parameter Map=================");
            paramMap.entrySet().forEach(x -> {
                logger.info(">>>>>" + x.getKey() + "=" + Joiner.on(",").join(x.getValue()));
            });

            logger.info("===================================================================");
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}